package com.meida.module.bus.provider.controller;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.log.StaticLog;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.springmvc.base.BaseController;
import com.meida.module.bus.client.entity.*;
import com.meida.module.bus.client.entity.srmapi.basedata.SrmContracts;
import com.meida.module.bus.client.entity.srmapi.basedata.SrmPurchaseorderdetail;
import com.meida.module.bus.provider.api.util.ApiConstants;
import com.meida.module.bus.provider.api.util.PmsOaUtil;
import com.meida.module.bus.provider.api.util.PmsApiUtil;
import com.meida.module.bus.provider.api.util.PmsOaUtil;
import com.meida.module.bus.provider.api.util.PmsToolUtil;
import com.meida.module.bus.provider.service.*;
import com.meida.module.bus.provider.service.srmservice.SrmSqlserCommonService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 200材料计划表控制器
 *
 * @author flyme
 * @date 2020-10-22
 */
@RestController
@RequestMapping("/bus/bmep/")
public class BusMaterialPlan200Controller extends BaseController<BusMaterialPlan200Service, BusMaterialPlan200> {
    @Autowired
    private BusVersionService busVersionService;
    @Autowired
    private BusMaterialSrmService srmService;
    @Autowired
    private BusMaterialSrmSubService srmSubService;
    @Autowired
    private SrmSqlserCommonService commonService;
    @Autowired
    private BusMaterialService busMaterialService;
    @Autowired
    private PmsApiUtil pmsApiUtil;
    @Autowired
    private PmsOaUtil pmaOaUtil;

    @ApiOperation(value = "200材料计划表-分页列表", notes = "200材料计划表分页列表")
    @GetMapping(value = "page")
    public ResultBody pageList(@RequestParam(required = false) Map params) {
        return bizService.pageList(params);
    }


    @ApiOperation(value = "200材料计划表-列表", notes = "200材料计划表列表")
    @GetMapping(value = "list")
    public ResultBody list(@RequestParam(required = false) Map params) {
        return bizService.listEntityMap(params);
    }

    @ApiOperation(value = "200材料计划表-添加", notes = "添加200材料计划表")
    @PostMapping(value = "save")
    public ResultBody save(@RequestParam(required = false) Map params) {
        return bizService.add(params);
    }

    @ApiOperation(value = "200材料计划表-更新", notes = "更新200材料计划表")
    @PostMapping(value = "update")
    public ResultBody update(@RequestParam(required = false) Map params) {
        return bizService.edit(params);
    }

    @ApiOperation(value = "200材料计划表-删除", notes = "删除200材料计划表")
    @PostMapping(value = "remove")
    public ResultBody remove(@RequestParam(required = false) Map params) {
        return bizService.delete(params);
    }

    @ApiOperation(value = "合并200数据", notes = "合并200数据")
    @PostMapping(value = "margeplan200")
    public ResultBody margeplan200(@RequestParam(required = false) Map params) {
        return bizService.mergeplan200(params);
    }

    @ApiOperation(value = "200材料计划表-详情", notes = "200材料计划表详情")
    @GetMapping(value = "get")
    public ResultBody get(@RequestParam(required = false) Map params) {
        return bizService.get(params);
    }

    @ApiOperation(value = "材料修改变更", notes = "材料修改变更")
    @PostMapping(value = "copyAndUpdate")
    public ResultBody copyAndUpdate(@RequestParam(required = false) Map params) {
        ResultBody body = bizService.copyAndUpdateplan(params);
//        Long projectId=Long.parseLong(params.get("projectId").toString());
//        pmaOaUtil.updateMaterialBase(projectId, ApiConstants.VER_200, ApiConstants.INT_ZERO);
        return body;
    }

    @ApiOperation(value = "200材料-导出模板", notes = "200材料-导出模板")
    @PostMapping(value = "export200planTemplate")
    public void export200planTemplate(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false) Map params) {
        bizService.export(params, request, response, "200材料计划", "200材料计划", "busmaterialPlan200ExportHandler");
    }

    @ApiOperation(value = "200材料-导入数据", notes = "200材料-导入数据")
    @PostMapping(value = "import200UpdateData")
    public ResultBody import200UpdateData(@RequestParam(required = false) Map params, @RequestParam("file") MultipartFile file) {
        ResultBody resultBody = bizService.importPlan200Data(file, params);
//        Long projectId=Long.parseLong(params.get("projectId").toString());
//        pmaOaUtil.updateMaterialBase(projectId, ApiConstants.VER_200, ApiConstants.INT_ZERO);
        return resultBody;
    }

    @ApiOperation(value = "100材料计划表-分页列表", notes = "100材料计划表分页列表")
    @GetMapping(value = "pagedetail")
    public ResultBody pagedetail(@RequestParam(required = false) Map params) {
        return bizService.pageList(params);
    }


    @ApiOperation(value = "获取历史版本", notes = "获取历史版本")
    @GetMapping(value = "selectVersionList")
    public ResultBody selectVersionList(@RequestParam(required = false) Map params) {
        List<EntityMap> entityMapList = bizService.selectVersionList(params);
        return ResultBody.ok().data(entityMapList);
    }

    @ApiOperation(value = "200分包-SRM系统价格同步", notes = "200分包-SRM系统价格同步")
    @PostMapping(value = "syncSrmPrice")
    public ResultBody syncSrmPrice(@RequestParam(required = true) Long projectId) {
        // 同步SRM的价格逻辑
        //【SRM材料价格】同步到PMS母表的【预算成本单价_未税_主材价格】
        //->重新计算【预算成本单价_未税_综合单价】、
        //【预算成本合价_未税_主材价】、
        //【预算成本合价_未税_合计】

        Map<String, Object> searchMap = Maps.newHashMap();
        searchMap.put(ApiConstants.MAP_PROJECTID, projectId);
        searchMap.put(ApiConstants.MAP_PARENTID, 0);
        Collection<BusMaterialPlan200> busMaterialPlan200s = bizService.listByMap(searchMap);
        if(0 == busMaterialPlan200s.size()) {
            searchMap = Maps.newHashMap();
            searchMap.put(ApiConstants.MAP_PROJECTID, projectId);
            busMaterialPlan200s = bizService.listByMap(searchMap);
        }
        if (0 != busMaterialPlan200s.size()) {
            List<BusMaterialSrmSub> srmSubsList = pmsApiUtil.getBusMaterialSrmSubsByProjectId(projectId, ApiConstants.WZ_PLANDATA);
            // 损耗MAP
            Map<Long, BigDecimal> syncIdForLostMap = Maps.newHashMap();
            // key 材料计划主key value
            Map<Long, Long> syncIdMap = Maps.newHashMap();
            List<Long> syncIdList = Lists.newArrayList();
            //  200版本的所有【材料】父级节点数据，
            busMaterialPlan200s.stream().forEach(plan200Obj -> {
                // 基于100版计划下达的材料申请
                if (srmSubsList.stream().anyMatch(srmSubOject -> srmSubOject.getMaterialPlanId().equals(plan200Obj.getPackagePlan100Id()))) {
                    syncIdMap.put(plan200Obj.getPackagePlan100Id(), plan200Obj.getMaterialPlanId());
                    syncIdList.add(plan200Obj.getPackagePlan100Id());
                    syncIdForLostMap.put(plan200Obj.getPackagePlan100Id(), plan200Obj.getLoss());

                } else if (srmSubsList.stream().anyMatch(srmSubOject -> srmSubOject.getMaterialPlanId().equals(plan200Obj.getMaterialPlanId()))) {
                    // 基于200版计划下达的材料申请
                    syncIdMap.put(plan200Obj.getMaterialPlanId(), 0L);
                    syncIdList.add(plan200Obj.getMaterialPlanId());
                    syncIdForLostMap.put(plan200Obj.getMaterialPlanId(), plan200Obj.getLoss());
                }
//                //  1：有对应的100版本数据
//                if (PmsToolUtil.checkLong(plan200Obj.getPackagePlan100Id())) {
//                    syncIdMap.put(plan200Obj.getPackagePlan100Id(), plan200Obj.getMaterialPlanId());
//                    syncIdList.add(plan200Obj.getPackagePlan100Id());
//                } else {
//                    //  2：无对应的100版本数据
//                    syncIdMap.put(plan200Obj.getMaterialPlanId(), 0L);
//                    syncIdList.add(plan200Obj.getMaterialPlanId());
//                }
            });

            StaticLog.info("syncIdList: " + syncIdList);
            StaticLog.info("syncIdList: " + syncIdList);
            StaticLog.info("syncIdList: " + syncIdList);
            // key 计划ID value 平均价格
            Map<Long, BigDecimal> syncPriceMap = Maps.newHashMap();
            List<Long> sycnPricePalnIds = Lists.newArrayList();
            //  获取100、200版本对应的SRM关联表数据。
            if (0 < syncIdList.size()) {
                syncIdList.stream().forEach(syncId -> {
                    Map<String, Object> filterMap = Maps.newHashMap();
                    filterMap.put(ApiConstants.MAP_MATERIALPLANID, syncId);
                    Collection<BusMaterialSrmSub> srmSubs = srmSubService.listByMap(filterMap);
                    // 一行PMS计划明细，可以对应多条SRM采购订单明细
                    if (0 < srmSubs.size()) {
                        List<Long> srmDetailIdsAll = Lists.newArrayList();
                        // 读取对应采购明细id，对应的价格数据。
                        srmSubs.stream().forEach(srmSubObj -> {
                            srmDetailIdsAll.add(srmSubObj.getPurchaseorderDetailid());
                        });
                        List<Long> srmDetailIds = srmDetailIdsAll.stream().distinct().collect(Collectors.toList());
                        Long[] srmDetailIdsArray = srmDetailIds.toArray(new Long[0]);
                        List<SrmPurchaseorderdetail> srmPurchaseorderdetails = commonService.getSrmPurchaseorderdetailByIds(srmDetailIdsArray);
                        BigDecimal contSum = BigDecimal.ZERO;
                        BigDecimal amountSum = BigDecimal.ZERO;
                        if (0 < srmPurchaseorderdetails.size()) {
                            for(SrmPurchaseorderdetail srmDetailObj : srmPurchaseorderdetails) {
                                contSum = NumberUtil.add(srmDetailObj.getBuyerQty(), contSum);
                                amountSum = NumberUtil.add(NumberUtil.mul(NumberUtil.mul(srmDetailObj.getDiscountnotaxPrice(), srmDetailObj.getBuyerQty()), srmDetailObj.getExchange()), amountSum);
                            }
                            if(!BigDecimal.ZERO.equals(contSum)) {
                                syncPriceMap.put(syncId, NumberUtil.mul(NumberUtil.div(amountSum, contSum), syncIdForLostMap.get(syncId)));
                                sycnPricePalnIds.add(syncId);
                            }
                        }
                    }
                });
                if(0 < sycnPricePalnIds.size()) {
                    List<BusMaterial> busMaterials = Lists.newArrayList();
                    sycnPricePalnIds.stream().forEach(syncId->{
                        BusMaterialPlan200 busMaterialPlan200 = null;
                        // 基于100版计划下达的材料申请
                        if(0L != syncIdMap.get(syncId)) {
                            busMaterialPlan200 = bizService.getById(syncIdMap.get(syncId));
                        } else {
                            // 基于200版计划下达的材料申请
                            busMaterialPlan200 = bizService.getById(syncId);
                        }
                        BusMaterial busMaterial = busMaterialService.getById(busMaterialPlan200.getMaterialId());
                        //->重新计算
                        // 预算成本单价_未税_主材价】
                        busMaterial.setMainPrice(syncPriceMap.get(syncId));
                        // 预算成本单价_未税_综合 单价】
                        busMaterial.setSyntheticalPrice(syncPriceMap.get(syncId));

                        //【预算成本合价_未税_主材价】
                        busMaterial.setMainAmount(NumberUtil.mul(syncPriceMap.get(syncId), busMaterialPlan200.getCostQuantity200()));
                        //【预算成本合价_未税_合计】
                        busMaterial.setSyntheticalAmount(NumberUtil.mul(syncPriceMap.get(syncId), busMaterialPlan200.getCostQuantity200()));
                        busMaterials.add(busMaterial);
                    });
                    if(0 < busMaterials.size()) {
                        //  反写会母表价格
                        busMaterialService.updateBatchById(busMaterials);
                    }
                }

                //  反写会母表价格




                //【SRM分包价格】同步到PMS母表的【预算成本单价_未税_安装价格】
                //->重新计算【预算成本单价_未税_综合单价】、
                //【预算成本合价_未税_安装价】、
                //【预算成本合价_未税_合计】


            }
        } else {
            return ResultBody.ok("无价格需要同步！");
        }
        return ResultBody.ok();
    }

    @ApiOperation(value = "判断材料行是否存在变更中待审核的数据", notes = "判断材料行是否存在变更中待审核的数据")
    @GetMapping(value = "checkUnderReview")
    public ResultBody checkHasUnderReviewRecord(@RequestParam Long materialPlanId) {
        CriteriaUpdate<BusMaterialPlan200> cu = new CriteriaUpdate();
        cu.eq("parentId", materialPlanId);
        cu.eq("applayStatus", 1);//审批中
        int count = bizService.count(cu);
        if(count > 0) {
            return ResultBody.ok().data("Y");
        }
        return ResultBody.ok().data("N");
    }

}